package com.example.practice;


import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;


/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment_6 extends Fragment {
    private TimerTask timerTask;
    private View view;
    private GridView list6;
    private Timer timer;
    private SQLiteDatabase db;
    public Fragment_6() {
        // Required empty public constructor
    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view=inflater.inflate(R.layout.fragment_6, container, false);
        initView();
        SqliteUsers sUsers = new SqliteUsers(getContext());
        db= sUsers.getReadableDatabase();
        timer=new Timer();
        timerTask=new TimerTask(){
            @Override
            public void run() {
                initData();
            }
        };
        timer.schedule(timerTask,0,3000);
        return view;
    }
    private interface BlogSever{
        @GET("getAirCondition")
        Call<ResponseBody> getBlog();
    }
    private void initData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        BlogSever blogSever = retrofit.create(BlogSever.class);
        Call<ResponseBody> blog = blogSever.getBlog();
        blog.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    List<Environmental> list = new ArrayList<>();
                    Environmental environmental = new Gson().fromJson(string, Environmental.class);
                    list.add(environmental);
                    List<String> list1=new ArrayList<>();
                    List<String> list2=new ArrayList<>();
                    list1.add(list.get(0).get温度()+"");
                    list1.add(list.get(0).get相对湿度()+"");
                    list1.add(list.get(0).get紫外线强度()+"");
                    list1.add(list.get(0).getCo2()+"");
                    list1.add(list.get(0).get_$Pm2596()+"");
                    String s =(int)(Math.random()*10)+"";
                    list1.add(s);
                    list2.add("温度");
                    list2.add("湿度");
                    list2.add("光照");
                    list2.add("CO2");
                    list2.add("PM2.5");
                    list2.add("道路状态");
                    ContentValues values = new ContentValues();
                    values.put("weather1",list.get(0).get温度());
                    values.put("weather2",list.get(0).get相对湿度());
                    values.put("weather3",list.get(0).get紫外线强度());
                    values.put("weather4",list.get(0).getCo2());
                    values.put("weather5",list.get(0).get_$Pm2596());
                    values.put("weather6",s);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
                    Date date = new Date(System.currentTimeMillis());
                    values.put("weather7",simpleDateFormat.format(date));
                    db.insert("weather",null,values);

                    Cursor info1;
                    info1= db.query("weather", null, null,null, null, null, null);
                    for(;info1.getCount()>20;){
                        info1.moveToFirst();
                        db.delete("weather","weather7=?", new String[]{info1.getString(info1.getColumnIndex("weather7"))});
                        info1=db.query("weather", null, null,null, null, null, null);
                    }
                    list6.setAdapter(new GridAdapter(list2,list1));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    private void initView() {
        list6=view.findViewById(R.id.list_6);

    }
    private class GridAdapter extends BaseAdapter{
        List<String> list1;
        List<String> list2;
        public GridAdapter(List<String> list1,List<String> list2) {
            this.list1=list1;
            this.list2=list2;
        }
        @Override
        public int getCount() {
            return list1.size();
        }
        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        private class ViewHolder{
            TextView textView1;
            TextView textView2;
        }
        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if(view==null){
                view=LayoutInflater.from(getContext()).inflate(R.layout.huanjing_layout,null);
                holder=new ViewHolder();
                holder.textView1 = view.findViewById(R.id.aText_6);
                holder.textView2= view.findViewById(R.id.bText_6);
                view.setTag(holder);
            }else {
                holder= (ViewHolder) view.getTag();
            }
            holder.textView1.setText(list1.get(i));
            if(Integer.parseInt(list2.get(i))>100){
            holder.textView1.setBackgroundColor(Color.parseColor("#FF0000"));
            }
            holder.textView2.setText(list2.get(i));
            holder.textView1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SharedPreferences sp=getActivity().getSharedPreferences("www",getActivity().MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("www",i+"");
                    edit.apply();
                    Intent intent = new Intent(getContext(), SuccessActivity.class);
                    intent.putExtra("sss",1);
                    getActivity().startActivity(intent);
                }
            });
            return view;
        }
    }
}
